package cn.jantd.modules.system.controller;

import cn.jantd.core.annotation.AutoLog;
import cn.jantd.core.api.vo.Result;
import cn.jantd.core.system.vo.LoginUser;
import cn.jantd.modules.system.entity.SerServer;
import cn.jantd.modules.system.service.ISerServerService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.zstack.sdk.*;

import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/sys/serVirtual")
@Slf4j
public class SerVirtualController {

    @Autowired
    ISerServerService serServerService;

    /*
     * 申请控制台
     * */
    @AutoLog(value = "申请控制台")
    @ApiOperation(value = "申请控制台")
    @GetMapping(value = "applyConsole")
    @ResponseBody
    public Map<String,String> applyConsole(){

        //查找user表里的id在session里取当前用户，取到他的id值（request对象）
        //List<SysUser> user=sysuserService.select(t);
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        System.out.println("shuchukanakn0:+++++++++"+user);
        String username=user.getUsername();
        System.out.println("数据输出username："+username);
        //sysuuid
        List<SerServer> uuidList = serServerService.selectByUuid(username);
        System.out.println("数据输出uuidlist："+uuidList);
/*      String useruuid=uuidList.get(0).getUuid();*/

       /* System.out.println("输出3：  "+useruuid);   */  //输出的却不是当前用户的uuid，是它的第一个uuid
        Map<String,String> object = new HashMap<String,String>();
        Integer instance=0;
        String addrResult = new String();
        String console1="1";
        try {
            String zstackServerHostname1 = "192.168.5.139";  //请输入zstack的管理节点的ip地址
            String accountName1 = "admin";        //请输入zstack的账号
            String password1 = "password";       //请输入zstack的账号密码
            ZSClient.configure(           //客户机配置
                    new ZSConfig.Builder()                      //启动项
                            .setHostname(zstackServerHostname1)
                            .setPort(8080)
                            .setContextPath("zstack")
                            .build()
            );

            String sessionId = getSessionByLoginAccount(accountName1, password1);
            GetLoginCaptchaAction action = new GetLoginCaptchaAction();

            //获取双因子秘钥
            GetTwoFactorAuthenticationSecretAction getaction = new GetTwoFactorAuthenticationSecretAction();
            getaction.name = "admin";
            getaction.password = "password";
            getaction.type = "account";
            GetTwoFactorAuthenticationSecretAction.Result res = getaction.call();
            action.resourceName = "zone"; //资源名称
            action.loginType = "account";//登录类型
            GetLoginCaptchaAction.Result cap = action.call();

            LogInByAccountAction loginaction = new LogInByAccountAction();
            loginaction.accountName = "admin";
            loginaction.password = "password";//需要对密码进行SHA-512算法加密
            /*获取验证码*/
            loginaction.captchaUuid = cap.value.getCaptchaUuid();   //验证码的uuid
            loginaction.verifyCode = cap.value.getCaptcha();           //验证码
            LogInByAccountAction.Result login = loginaction.call();


            /*查询云主机*/
            QueryVmInstanceAction vmAction = new QueryVmInstanceAction();
            vmAction.sessionId = sessionId;
            QueryVmInstanceAction.Result result = vmAction.call();


            result.throwExceptionIfError();
            List<VmInstanceInventory> vmList = result.value.getInventories();
            GetVmConsoleAddressAction vcAction = new GetVmConsoleAddressAction();


            for (int a = 0; a < uuidList.size(); a++) {
                String useruuid = uuidList.get(a).getUuid();
                System.out.println("输出2：  " + uuidList.get(a).getUuid());


         /*   for(int j=0;j<vmList.size();j++) {


                    System.out.println("11111:       " + j);
                    if (vmList.get(j).getUuid().equals(useruuid)) {
                        instance = j;
                        System.out.println(instance);
                        System.out.println(vmList.get(instance).getName());
                        System.out.println(vmList.get(instance).getUuid());
                        break;
                    }

            }*/
                System.out.println(String.format("查询云主机列表成功，查询到%s台云主机",
                        vmList != null ? vmList.size() : 0));

                System.out.println(instance);
                System.out.println(vmList.get(instance).getName());
                System.out.println(vmList.get(instance).getUuid());
                //获取云主机控制台地址和访问协议
                /*       String hostname="centos7";
                 */

                vcAction.uuid = useruuid;
                System.out.println("云主机的uuid是：" + vcAction.uuid);
                vcAction.sessionId = sessionId;
                System.out.println("云主机的sessionId是：" + vcAction.sessionId);
                GetVmConsoleAddressAction.Result get = vcAction.call();
                System.out.println(get.value.getHostIp());
                System.out.println(get.value.getPort());
                System.out.println(get.value.getProtocol());
                //获取云主机控制台地址和访问协议
                //请求控制台访问地址
                RequestConsoleAccessAction request = new RequestConsoleAccessAction();
                request.vmInstanceUuid = useruuid;
                System.out.println(request.vmInstanceUuid);
                request.sessionId = sessionId;
                RequestConsoleAccessAction.Result req = request.call();
                String token = req.value.getInventory().getToken();
                Integer port = req.value.getInventory().getPort();
                String scheme = req.value.getInventory().getScheme();
                String hostname1 = req.value.getInventory().getHostname();

                System.out.println(token);
                System.out.println(scheme);
                System.out.println(port);
                System.out.println(hostname1);
                System.out.println(req.value.getInventory());
                System.out.println(scheme + "://" + hostname1 + ":5000/thirdparty/vnc_auto.html?host=" + hostname1
                        + "&port=" + port + "&token=" + token);
                String addr = scheme + "://" + hostname1 + ":5000/thirdparty/vnc_auto.html?host=" + hostname1
                        + "&port=" + port + "&token=" + token;
                addrResult = addr;
            }
        }catch(Exception e){
            console1="0";
        }
        object.put("console1",console1);
        object.put("addrResult",addrResult);
        return object;
    }



    private static String getSessionByLoginAccount(String accountName, String password) {
        LogInByAccountAction action = new LogInByAccountAction();
        action.accountName = accountName;
        action.password = encryptToSHA512(password);

        LogInByAccountAction.Result result = action.call();
        result.throwExceptionIfError();
        System.out.println("登录成功");
        return result.value.getInventory().getUuid();
    }

    private static String getSessionByLoginAccount1(String accountName1, String password1) {
        LogInByAccountAction action = new LogInByAccountAction();
        action.accountName = accountName1;
        action.password = encryptToSHA512(password1);

        LogInByAccountAction.Result result = action.call();
        result.throwExceptionIfError();
        System.out.println("登录成功");
        return result.value.getInventory().getUuid();
    }

    private static String encryptToSHA512(String input) {
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-512");   //SHA-512算法（使用算法加密）
            md.reset();
            md.update(input.getBytes("utf8"));
            BigInteger bigInteger = new BigInteger(1, md.digest());
            return String.format("%0128x", bigInteger);
        } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }

    /*
     * 申请开启云主机
     * */
    @AutoLog(value = "启动云主机")
    @ApiOperation(value = "启动云主机")
    @GetMapping(value = "applyStart")
    @ResponseBody
    public Map<String,String> applyStart() {
        Map<String, String> object = new HashMap<String, String>();
        StartVmInstanceAction action = new StartVmInstanceAction();
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        System.out.println("shuchukanaknstop:+++++++++" + user);
        String username = user.getUsername();
        System.out.println("数据输出username的stop：" + username);
        //sysuuid
        List<SerServer> uuidList = serServerService.selectByUuid(username);
        System.out.println("数据输出uuidlist是什么：" + uuidList);
        for(int i=0;i<uuidList.size();i++) {
            String useruuid = uuidList.get(i).getUuid();
            if(null!=useruuid){
                action.uuid = useruuid;

            }else{
                System.out.println("uuid为空！");
            }

        }
        Integer instance = 0;
        String addrResult = new String();
        String console1 = "1";
        try {
            String zstackServerHostname1 = "192.168.5.139";  //请输入zstack的管理节点的ip地址
            String accountName1 = "admin";        //请输入zstack的账号
            String password1 = "password";       //请输入zstack的账号密码
            ZSClient.configure(           //客户机配置
                    new ZSConfig.Builder()                      //启动项
                            .setHostname(zstackServerHostname1)
                            .setPort(8080)
                            .setContextPath("zstack")
                            .build()
            );
            String sessionId = getSessionByLoginAccount(accountName1, password1);
            /*          GetLoginCaptchaAction loginaction = new GetLoginCaptchaAction();*/

            action.sessionId = sessionId;
            StartVmInstanceAction.Result res = action.call();
            System.out.println("看看输出的res是什么：+++++++++"+res);
            addrResult= String.valueOf(res);

        }catch(Exception e){
            console1="0";
        }
        object.put("console1",console1);
        object.put("addrResult",addrResult);
        return object;
    }



    /*
     * 申请停止云主机
     * */
    @AutoLog(value = "停止云主机")
    @ApiOperation(value = "停止云主机")
    @GetMapping(value = "applyStop")
    @ResponseBody
    public Map<String,String> applyStop() {
        Map<String, String> object = new HashMap<String, String>();
        StopVmInstanceAction action = new StopVmInstanceAction();
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        System.out.println("shuchukanaknstop:+++++++++" + user);
        String username = user.getUsername();
        System.out.println("数据输出username的stop：" + username);
        //sysuuid
        List<SerServer> uuidList = serServerService.selectByUuid(username);
        System.out.println("数据输出uuidlist是什么：" + uuidList);

        for(int i=0;i<uuidList.size();i++) {
            String useruuid = uuidList.get(i).getUuid();
            if(null!=useruuid){
                action.uuid = useruuid;
            }else{
                System.out.println("uuid为空！");
            }

        }
        action.type = "grace";
        Integer instance = 0;
        String addrResult = new String();
        String console1 = "1";
        try {
            String zstackServerHostname1 = "192.168.5.139";  //请输入zstack的管理节点的ip地址
            String accountName1 = "admin";        //请输入zstack的账号
            String password1 = "password";       //请输入zstack的账号密码
            ZSClient.configure(           //客户机配置
                    new ZSConfig.Builder()                      //启动项
                            .setHostname(zstackServerHostname1)
                            .setPort(8080)
                            .setContextPath("zstack")
                            .build()
            );
            String sessionId = getSessionByLoginAccount(accountName1, password1);
            /*          GetLoginCaptchaAction loginaction = new GetLoginCaptchaAction();*/

            action.sessionId = sessionId;
            StopVmInstanceAction.Result res = action.call();
            System.out.println("看看输出的res是什么：+++++++++"+res);
            addrResult= String.valueOf(res);

        }catch(Exception e){
            console1="0";
        }
        object.put("console1",console1);
        object.put("addrResult",addrResult);
        return object;
    }


    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "我的服务列表管理-通过id删除")
    @ApiOperation(value = "我的服务列表管理-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<SerServer> delete(@RequestParam(name = "id", required = true) String id) {
        Result<SerServer> result = new Result<>();
        SerServer server = serServerService.getById(id);
        if (server == null) {
            result.error500("未找到对应实体");
        } else {
            boolean ok = serServerService.removeById(id);
            if (ok) {
                result.success("删除成功!");
            }
        }

        return result;
    }


}



